import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

import userApi from "../api/user"
import storage from '../utils/auth'

export default new Vuex.Store({
  state: {
    token :  storage.getToken() ? storage.getToken() : "",
    userInfo :  storage.getUserInfo() ? storage.getUserInfo() : "",
  },
  mutations: {
    saveToken(state,token){
      state.token = token;
      storage.setToken(token)
    },
    saveUserInfo(state,userInfo){
      state.userInfo = userInfo;
      storage.setUserInfo(userInfo)
    }
  },
  actions: {
    //登录方法
    login({commit},loginForm){
      return new Promise((resolve, reject)=>{
        userApi.doLogin(loginForm.username,loginForm.password).then(response=>{
          if(response.data.flag){
            let token = response.data.data.token;
            commit("saveToken",token)
          }
          resolve(response)
        }).catch(error=>{
          reject(error)
        })
      })
    },
    //获取用户信息方法
    getUserInfo({commit}){
      return new Promise((resolve,reject)=>{
        userApi.doUserInfo().then(response=>{
          resolve(response)
          if(response.data.flag){
            let userInfo = response.data.data;
            commit("saveUserInfo",userInfo)
          }
          
        }).catch(error=>{
          reject(error)
        })
      })
    },
    //退出登录方法
    clearLogout({commit}){
      return new Promise((resolve, reject)=>{
        //调用退出登录接口
        userApi.doLogout().then(response=>{
          resolve(response)
          if(response.data.flag){ 
            //1. 清除vuex里面存储的token和用户信息
            commit("saveToken",null);
            commit("saveUserInfo",null);
            //2. 清除本地存储的token和用户信息
            storage.removeTokenAndUserInfo()
          }
        }).catch(error=>{
          reject(error)
        })
      })
      
    }
  },
  modules: {
  },
});
